<template>
  <div id="app">
    <transition :name="transitionName">
      <keep-alive>
        <router-view />
      </keep-alive>
    </transition>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      transitionName: "",
    };
  },

  watch: {
    $route(to, from) {
      /**
       * 这个函数能监听页面的前进后退--可信任
       * 我们需要维护一个路由数组，由此判断前进后退
       */
      let history = window.sessionStorage.getItem("history");

      if (history == null) {
        history = [];
        history.push(from.fullPath);
      } else {
        history = JSON.parse(history);
      }

      let len = history.length;
      if (len >= 2) {
        let oldPage = history[len - 2];
        let newPage = to.fullPath;
        let curPage = history[len - 1];

        if (curPage != "/login") {
          if (oldPage == newPage) {
            //相等即为返回操作
            history.pop();
            this.transitionName = "slide-right";
          } else {
            history.push(to.fullPath);
            this.transitionName = "slide-left";
          }
        } else {
          history.splice(0, len - 1);
          history.push(to.fullPath);
        }
      } else {
        this.transitionName = "slide-left";
        history.push(to.fullPath);
      }

      window.sessionStorage.setItem("history", JSON.stringify(history));
    },
  },
};
</script>

<style>
body,
html {
  width: 375px;
  height: 667px;
}

#app {
  width: 100%;
  height: 100%;
  background-color: #f2f2f2;
}
#app {
  position: relative;
}
#app > * {
  position: absolute;
  width: 100%;
}

.slide-right-enter-active,
.slide-right-leave-active,
.slide-left-enter-active,
.slide-left-leave-active {
  will-change: transform;
  transition: all 0.2s;
  position: absolute;
}
.slide-right-enter {
  transform: translate3d(-100%, 0, 0);
}
.slide-right-leave-active {
  transform: translate3d(100%, 0, 0);
}
.slide-left-enter {
  transform: translate3d(100%, 0, 0);
}
.slide-left-leave-active {
  transform: translate3d(-100%, 0, 0);
}
</style>
